package com.asistencia.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.asistencia.businness.ClassroomBusiness;
import com.asistencia.businness.CourseBusinness;
import com.asistencia.businness.ProfessorBusiness;
import com.asistencia.businness.ScheduleBusiness;
import com.asistencia.businness.SemesterBusiness;
import com.asistencia.domain.Classroom;
import com.asistencia.domain.Course;
import com.asistencia.domain.Professor;
import com.asistencia.domain.Schedule;
import com.asistencia.domain.Semester;
import com.asistencia.util.Constant;

@Controller
public class ScheduleController {

	@Autowired
	private CourseBusinness courseBusinness;
	@Autowired
	private SemesterBusiness semesterBusiness;
	@Autowired
	private ScheduleBusiness scheduleBusiness;
	@Autowired
	private ClassroomBusiness classroomBusiness;
	@Autowired
	private ProfessorBusiness professorBusiness;

	@RequestMapping(value = "/programmed-classes.tecsup", method = RequestMethod.GET)
	public String listScheduleBySemesterCourse(
			@RequestParam(value = "ic", required = true) Integer idCourse,
			@RequestParam(value = "is", required = true) Integer idSemester,
			ModelMap modelMap) {

		List<Schedule> listSchedules = scheduleBusiness.listByCourseSemester(
				idCourse, idSemester);

		Course course = courseBusinness.getCourseById(idCourse);
		Semester semester = semesterBusiness.getById(idSemester);

		if (listSchedules != null) {
			for (Schedule schedule : listSchedules) {
				Classroom classroom = classroomBusiness.getById(schedule
						.getMyClassroom().getIdClassroom());
				Professor professor = professorBusiness.getById(schedule
						.getMyProfessor().getIdProfessor());
				schedule.setMyClassroom(classroom);
				schedule.setMyProfessor(professor);
			}
		}

		modelMap.addAttribute("course", course);
		modelMap.addAttribute("semester", semester);
		modelMap.addAttribute("listSchedules", listSchedules);

		return "schedule-course";

	}

	@RequestMapping(value = "/finish-class.tecsup", method = RequestMethod.POST)
	public String finishClass(
			@RequestParam(value = "idClass", required = true) Integer idClass,
			@RequestParam(value = "password", required = true) String password,
			HttpSession session) {
		Professor professor = (Professor) session.getAttribute(Constant.USER_IN_SESSION);
		if(professorBusiness.loginProfessor(professor.getUsername(), password) != null){
			scheduleBusiness.updateScheduleById("FINALIZADA", idClass);
		}
		return "redirect:/index.tecsup";
	}

}
